package cc.eddic.examinationsystem.web;

import cc.eddic.examinationsystem.core.BaseController;
import cc.eddic.examinationsystem.domain.Exam;
import cc.eddic.examinationsystem.domain.ExamStudent;
import cc.eddic.examinationsystem.dto.ExamModel;
import cc.eddic.examinationsystem.repository.ExamRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/exam")
public class ExamController  extends BaseController {
    public ExamController(ExamRepository examRepository) {
        this.examRepository = examRepository;
    }
    @GetMapping("/list")
    public String list(Model model) {
        List<Exam> examList=examRepository.findAll();
        List<ExamModel> examModelList=new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for(Exam exam:examList){
            String startTtime = df.format(exam.getExamAt());
            ExamModel examModel=new ExamModel(exam.getId(),exam.getName(),startTtime,exam.getTimeLimit(),exam.getTotalScore(),exam.getVersion());
            examModelList.add(examModel);
        }
        model.addAttribute("examList1", examModelList);
        return "exam-list";
    }

//    @GetMapping("/list")
//    public String list(Model model) {
//        model.addAttribute("dt", LocalDateTime.now());
//        model.addAttribute("examList1", examRepository.findAll());
//        return "exam-list";
//    }

    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("examModel", ExamModel.builder().build());
        return "exam-add";
    }
//
    @PostMapping(value = "/save",params = "save")
    public String save(@ModelAttribute @Valid ExamModel examModel, BindingResult bindingResult, Model model) throws ParseException {
        log.debug("examModel = {}", examModel);
        if (bindingResult.hasErrors()) {
            if (log.isDebugEnabled()) log.debug("bindingResult = {}", bindingResult);
            model.addAttribute("examModel",examModel);
            return "exam-add";
        }
            Exam exam;
            if (examModel.getId() == null) {
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime localDateTime = LocalDateTime.parse(examModel.getExamAt().replaceAll("T", " ") + ":00", df);
                exam = new Exam(examModel.getName(),localDateTime,examModel.getTimeLimit(),examModel.getTotalScore());
            } else {
                if (log.isDebugEnabled()) log.debug("edit : id = {}, version = {}", examModel.getId(), examModel.getVersion());
                val optionalExam = examRepository.findByIdAndVersion(examModel.getId(), examModel.getVersion());
                if (!optionalExam.isPresent()) {
                    if (log.isDebugEnabled()) log.debug("not found {}", examModel.getId());

                    bindingResult.reject("ERROR", String.format("找不到 Id = %d 且 Version = %d 的数据", examModel.getId(), examModel.getVersion()));
                    return "exam-add";
                }

                exam=optionalExam.get();
                exam.setName(examModel.getName());
                exam.setTotalScore(examModel.getTotalScore());
                exam.setTimeLimit(examModel.getTimeLimit());
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime localDateTime = LocalDateTime.parse(examModel.getExamAt().replaceAll("T", " ") + ":00", df);
                exam.setExamAt(localDateTime);

            }
            examRepository.save(exam);
            return "redirect:/exam/list";
    }

    @GetMapping("/del/{id}")
    public String del(@PathVariable("id") long id,Model model){
        examRepository.deleteById(id);
        model.addAttribute("examList1",examRepository.findAll());
        model.addAttribute("success","success");
        return "exam-list";
    }

    @GetMapping(value = "/find/{id}")
    public String find(@PathVariable long id, Model model) {
        Exam exam=examRepository.getById(id);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //获取数据库的时间“2022-02-09 10:21”，转化为前端需要的字符串格式的时间“2022-02-09T10:21”
        String startTtime = df.format(exam.getExamAt());
        ExamModel examModel=new ExamModel(exam.getId(),exam.getName(),startTtime,exam.getTimeLimit(),exam.getTotalScore(),exam.getVersion());
        model.addAttribute("examModel", examModel);

        return "exam-add";
    }


//    @PostMapping(value = "/update",params = "update")
//    public String update(@ModelAttribute ExamModel examModel) throws ParseException{
////        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
////        LocalDateTime localDateTime = LocalDateTime.parse(examNow.getExamAt().replaceAll("T", " ") + ":00", df);
//
//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime localDateTime = LocalDateTime.parse(examModel.getExamAt().replaceAll("T", " ") + ":00", df);
////        Exam exam=examRepository.findById(examNow.getId()).orElseThrow(() -> new RuntimeException("not found"));
//        Exam exam = new Exam(examModel.getName(), localDateTime, examModel.getTimeLimit(), examModel.getTotalScore());
////        exam.setName(examNow.getName());
////        System.out.print("xxxxxxxx"+exam.getId());
//        examRepository.save(exam);
//        return "redirect:/exam/list";
//    }


    private final ExamRepository examRepository;
}
